package org.victoria.market.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.victoria.market.api.IGoods;
import org.victoria.market.dao.DaoSupport;
import org.victoria.market.domain.Category;
import org.victoria.market.domain.Goods;
import org.victoria.market.utils.QueryHelper;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by thanatos on 15-9-13.
 */
@Service
@Transactional(rollbackFor = TException.class)
public class IGoodsImp implements IGoods.Iface{

    private static final Logger logger = LoggerFactory.getLogger("IGoodsImp");
    @Autowired SolrServer mSolrServer;
    @Autowired DaoSupport daoSupport;

    @Override
    public String save(String obj) throws TException {
        try {
            Goods goods = JSON.toJavaObject(JSON.parseObject(obj), Goods.class);

            QueryHelper helper = daoSupport.openQueryHelper();

            helper.setNameSpace("Goods.saveOne")
                    .setValue(goods)
                    .dao().save();

            if (goods.getCategories()!=null && goods.getCategories().size()>0){
                for (Category item : goods.getCategories()){
                    helper.clear();
                    item = helper.setNameSpace("Category.findByNameAndPid")
                            .putValue("name", item.getName())
                            .putValue("pid", item.getParent().getId())
                            .dao().findOne();

                    helper.clear();
                    helper.setNameSpace("Goods.save2relation4category")
                            .putValue("gid", goods.getId())
                            .putValue("cid", item.getId())
                            .dao().save();
                }
            }

            mSolrServer.addBean(goods, -1);
            mSolrServer.commit();

            return goods.getId().toString();

        }catch (Exception e){
            e.printStackTrace();
            try {
                mSolrServer.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            throw new TException(e);
        }
    }

    @Override
    public void deleteOne(long id) throws TException{
        logger.info(">>>IGoodsImp.deleteOne>>>id>>>"+id);
        daoSupport.openQueryHelper()
                .setNameSpace("Goods.deleteOne")
                .setValue(id)
                .dao().deleteOne();

        try {
            mSolrServer.deleteByQuery("goods_id:" + id);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                mSolrServer.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public String findOne(long id) throws TException {
        QueryHelper helper = daoSupport.openQueryHelper();
        Goods goods = helper.setNameSpace("Goods.findOne")
                .setValue(id)
                .dao().findOne();

        if (goods==null)
            return null;

        JSONObject object = JSONObject.parseObject(JSON.toJSONString(goods));

        helper.clear();
        List<Category> categories = helper.setNameSpace("Category.findByGoods")
                .setValue(goods.getId())
                .dao().find();

        if (categories!=null && categories.size()>0){
            Category category = categories.get(0);
            object.put("category", findCategoryParent(category));
        }

        object.put("createOn", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(goods.getCreateOn()));

        return object.toJSONString();
    }

    @Override
    public String findByCategory(long cid) throws TException {
        JSONObject object = new JSONObject();
        QueryHelper helper = daoSupport.openQueryHelper();

        //category
        Category category = helper.setNameSpace("Category.findOne")
                .setValue(cid)
                .dao().findOne();

        JSONObject co = findCategoryParentAndBrothers(category);

        helper.clear();
        List<Goods> products = helper.setNameSpace("Goods.findByCategory")
                .setValue(cid)
                .dao().find();

        object.put("category", co);
        object.put("products", products);

        return object.toJSONString();
    }

    private JSONObject findCategoryParent(Category category){
        if (category==null)
            return null;
        JSONObject object = JSON.parseObject(JSON.toJSONString(category));
        QueryHelper helper = daoSupport.getQueryHelper();
        helper.clear();
        Category parent = helper.setNameSpace("Category.findParent")
                .setValue(category.getId())
                .dao().findOne();
        if (parent!=null){
            object.put("parent", findCategoryParent(parent));
        }
        return object;
    }

    private JSONObject findCategoryParentAndBrothers(Category category) {
        if (category==null)
            return null;
        JSONObject object = JSON.parseObject(JSON.toJSONString(category));
        QueryHelper helper = daoSupport.getQueryHelper();
        helper.clear();
        Category parent = helper.setNameSpace("Category.findParent")
                .setValue(category.getId())
                .dao().findOne();
        if (parent!=null){
            helper.clear();
            List<Category> brothers = helper.setNameSpace("Category.findBrother")
                    .putValue("pid", parent.getId())
                    .putValue("level", category.getLevel())
                    .dao().find();
            object.put("brothers", brothers);
            object.put("parent", findCategoryParentAndBrothers(parent));
        }
        return object;
    }

}
